from flask import request, jsonify
from routes import app
from services.vep_service import VepService

# from flask_login import login_required

# 创建 VepService 实例
vep_service = VepService()


# VEP Parameter Routes
@app.route("/vep_parameters", methods=['GET', 'POST'])
# @login_required
def vep_parameters():
    if request.method == 'POST':
        data = request.json
        vep_parameter = vep_service.add_vep_parameter(data)
        return jsonify(vep_parameter.to_dict()), 201
    elif request.method == 'GET':
        vep_parameters = vep_service.get_all_vep_parameters()
        return jsonify([param.to_dict() for param in vep_parameters]), 200


@app.route("/vep_parameters/<int:id>", methods=['GET', 'PUT', 'DELETE'])
# @login_required
def vep_parameter(id):
    if request.method == 'GET':
        vep_parameter = vep_service.get_vep_parameter(id)
        if vep_parameter:
            return jsonify(vep_parameter.to_dict()), 200
        else:
            return jsonify({'error': 'Not found'}), 404
    elif request.method == 'PUT':
        data = request.json
        updated_parameter = vep_service.update_vep_parameter(id, data)
        if updated_parameter:
            return jsonify(updated_parameter.to_dict()), 200
        else:
            return jsonify({'error': 'Not found'}), 404
    elif request.method == 'DELETE':
        if vep_service.delete_vep_parameter(id):
            return jsonify({'message': 'Deleted successfully'}), 200
        else:
            return jsonify({'error': 'Not found'}), 404


@app.route(
    "/vep_parameters_by_fields/<int:year>/<string:vepCity>/<string:vepDistrict>/<string:vepTown>/<string:vepName>",
    methods=['GET', 'PUT', 'DELETE'])
def vep_parameter_by_fields(year, vepCity, vepDistrict, vepTown, vepName):
    if request.method == 'GET':
        record = vep_service.get_vep_parameter_by_fields(year, vepCity, vepDistrict, vepTown, vepName)
        if record:
            return jsonify(record.to_dict()), 200
        else:
            return jsonify({'error': 'Not found'}), 404

    elif request.method == 'PUT':
        data = request.json
        print("vep_parameter_by_fields data", data)

        # 预处理数据，将 None 值转换为 0
        numeric_fields = ['averageOccupancyRate', 'dailyVisitorFlow', 'directSalesRevenue', 'perCapitaDailyConsumption'
            , 'processedProductsRevenue'
            , 'perCapitaDailyConsumption'
            , 'projectArea'
            , 'realEstateRevenue'
            , 'regulationServiceValue'
            , 'roomCount'
            , 'roomPrice'
            , 'ticketPrice'
            , 'tourismHealthRevenue'
            , 'townArea'
                          ]  # 根据实际模型字段调整
        for field in numeric_fields:
            if field in data and (data[field] is None or data[field] == ''):
                data[field] = 0
        print("vep_parameter_by_fields numeric_fields data", data)
        updated_record = vep_service.update_vep_parameter_by_fields(year, vepCity, vepDistrict, vepTown, vepName, data)
        if updated_record:
            return jsonify(updated_record.to_dict()), 200
        else:
            return jsonify({'error': 'Not found or failed to update'}), 404

    elif request.method == 'DELETE':
        deleted = vep_service.delete_vep_parameter_by_fields(year, vepCity, vepDistrict, vepTown, vepName)
        if deleted:
            return jsonify({'message': 'Deleted successfully'}), 200
        else:
            return jsonify({'error': 'Not found'}), 404


# VEP Result Routes
@app.route("/vep_results", methods=['GET', 'POST'])
# @login_required
def vep_results():
    if request.method == 'POST':
        data = request.json
        vep_result = vep_service.add_vep_result(data)
        return jsonify(vep_result.to_dict()), 201
    elif request.method == 'GET':
        vep_results = vep_service.get_all_vep_results()
        return jsonify([result.to_dict() for result in vep_results]), 200


@app.route("/vep_results/<int:id>", methods=['GET', 'PUT', 'DELETE'])
# @login_required
def vep_result(id):
    if request.method == 'GET':
        vep_result = vep_service.get_vep_result(id)
        if vep_result:
            return jsonify(vep_result.to_dict()), 200
        else:
            return jsonify({'error': 'Not found'}), 404
    elif request.method == 'PUT':
        data = request.json
        updated_result = vep_service.update_vep_result(id, data)
        if updated_result:
            return jsonify(updated_result.to_dict()), 200
        else:
            return jsonify({'error': 'Not found'}), 404
    elif request.method == 'DELETE':
        if vep_service.delete_vep_result(id):
            return jsonify({'message': 'Deleted successfully'}), 200
        else:
            return jsonify({'error': 'Not found'}), 404


@app.route("/vep_results_by_fields/<int:year>/<string:vepCity>/<string:vepDistrict>/<string:vepTown>/<string:vepName>",
           methods=['GET', 'PUT', 'DELETE'])
def vep_result_by_fields(year, vepCity, vepDistrict, vepTown, vepName):
    if request.method == 'GET':
        record = vep_service.get_vep_result_by_fields(year, vepCity, vepDistrict, vepTown, vepName)
        if record:
            return jsonify(record.to_dict()), 200
        else:
            return jsonify({'error': 'Not found'}), 404

    elif request.method == 'PUT':
        data = request.json

        # 预处理数据，将 None 值转换为 0
        numeric_fields = ['provisioningServices', 'regulatingServices', 'culturalServices', 'vepResult']  # 根据实际模型字段调整
        for field in numeric_fields:
            if field in data and (data[field] is None or data[field] == ''):
                data[field] = 0

        updated_record = vep_service.update_vep_result_by_fields(year, vepCity, vepDistrict, vepTown, vepName, data)
        if updated_record:
            return jsonify(updated_record.to_dict()), 200
        else:
            return jsonify({'error': 'Not found'}), 404

    elif request.method == 'DELETE':
        deleted = vep_service.delete_vep_result_by_fields(year, vepCity, vepDistrict, vepTown, vepName)
        if deleted:
            return jsonify({'message': 'Deleted successfully'}), 200
        else:
            return jsonify({'error': 'Not found'}), 404
